package com.common.sdk.net.download.db;

import java.util.HashMap;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.text.TextUtils;

import com.common.sdk.net.download.request.model.AbsDownloadInfo;
import com.common.sdk.net.download.request.model.DownloadGeneral;
import com.common.sdk.net.download.request.model.DownloadInfo;
import com.common.sdk.net.download.util.DownloadFilePathUtils;
import com.common.sdk.net.download.util.DownloadLog;

/**
 * 数据库辅助类，暂时当做缓存  最后将缓存和数据库分开
 * @author wenlonglv
 *
 */
public class DownloadFileDetailedHelper {

    /**
     * 将数据保存到file_detailed数据库
     * @param request
     * @return
     */
    protected static long setFileDetailed(DownloadInfo downloadInfo) {
        long num = 0;
        ContentValues values = requestToValues(downloadInfo);
        try {
            num = updateFileDetailed(downloadInfo.getKey(), values);
            if (num <= 0) {
                num = insertFileDetailed(values);
            }
        } catch (Exception e) {
            DownloadLog.error(e);
        }
        return num;
    }

    /**
     * 删除数据库
     * @param apkDownloadModel
     * @return 
     */
    protected static int deleteDownloadItem(DownloadInfo downloadInfo) {
        try {
            String key = downloadInfo.getKey();
            int result = deleteFileDetailed(key);
            // 置状态为已删除
            downloadInfo.deletedDownload();
            return result;
        } catch (Exception e) {
            DownloadLog.error(e);
        }
        return 0;
    }

    /***
     * 下载中更新或插入数据库
     * @param request 如果返回0 为错误，需要处理。大于0为正确
     */
    protected static long beginDownload(DownloadInfo apkDownloadModel) {
        long num = 0;
        ContentValues values = requestToValues(apkDownloadModel);
        try {
            num = updateFileDetailed(apkDownloadModel.getKey(), values);

            if (num <= 0) {
                num = insertFileDetailed(values);
                if (num <= 0) {
                    return num;
                }
            }
        } catch (Exception e) {
            DownloadLog.error(e);
        }

        return 0;
    }

    // @SuppressWarnings("unused")
    // private static DownloadInfo queryKeyFileDetailed(String key) {
    // SQLiteDatabase database = null;
    // Cursor cursor = null;
    // try {
    // database = DownloadSQLiteOpenHelper.getIntance().getReadableDatabase();
    // SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
    // qBuilder.setTables(DownloadDetailesTables.DOWNLOAD_DB_FILE_DETAILE);
    // String[] projection = { DownloadDetailesTables.KEY,
    // DownloadDetailesTables.DOWNLOAD_PATH,
    // DownloadDetailesTables.THREAD_NUM,
    // DownloadDetailesTables.DOWNLOAD_PRIORITY,
    // DownloadDetailesTables.PACKAGE_NAME, DownloadDetailesTables.FILE_VERSION
    // };
    // String selection = "";
    // cursor = qBuilder.query(database, projection, selection, null, null,
    // null, null, null);
    // while (cursor.moveToNext()) {
    // String keyCursor = cursor.getString(0);
    // String downloadPath = cursor.getString(1);
    // int threadNum = cursor.getInt(2);
    // int downloadPriority = cursor.getInt(3);
    // String packageName = cursor.getString(4);
    // String fileVersion = cursor.getString(5);
    // DownloadInfo downloadInfo = new
    // DownloadInfo(packageName,fileVersion,downloadPath, downloadPriority);
    // downloadInfo.setThreadNum(threadNum);
    // return downloadInfo;
    // }
    // } catch (Exception e) {
    // DownloadLog.error(e);
    // }
    // return null;
    // }

    /**
     * 不能变为public DatabaseCache调用
     * @param canterMap
     */
    protected static void queryAllFileDetailed(HashMap<String, DownloadInfo> canterMap) {
        SQLiteDatabase database = null;
        Cursor cursor = null;
        try {
            database = DownloadSQLiteOpenHelper.getIntance().getReadableDatabase();
            SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
            qBuilder.setTables(DownloadDetailesTables.DOWNLOAD_DB_FILE_DETAILE);
            String[] projection = { DownloadDetailesTables.KEY, DownloadDetailesTables.TYPE,
                    DownloadDetailesTables.STATE, DownloadDetailesTables.DOWNLOAD_PATH,
                    DownloadDetailesTables.FILESIZE, DownloadDetailesTables.THREAD_NUM,
                    DownloadDetailesTables.ALREADY_SIZE, DownloadDetailesTables.SD_PATH,
                    DownloadDetailesTables.DOWNLOAD_TIME, DownloadDetailesTables.ISBUILD,
                    DownloadDetailesTables.VERSION_CODE, DownloadDetailesTables.FILE_NAME,
                    DownloadDetailesTables.DOWNLOAD_PRIORITY, DownloadDetailesTables.PACKAGE_NAME,
                    DownloadDetailesTables.DOWNLOAD_PATH_TWO, DownloadDetailesTables.CATE_CODE,
                    DownloadDetailesTables.ICON_PATH, DownloadDetailesTables.SUFFIX_NAME,
                    DownloadDetailesTables.DOWNLOAD_SOURCE };
            String sortOrder = DownloadDetailesTables.DOWNLOAD_TIME + " DESC";
            cursor = qBuilder.query(database, projection, null, null, null, null, sortOrder, null);
            while (cursor.moveToNext()) {
                String key = cursor.getString(0);
                int type = cursor.getInt(1);
                int state = cursor.getInt(2);
                String download_path = cursor.getString(3);
                long fileSize = cursor.getLong(4);
                int threadNum = cursor.getInt(5);
                int alreadyDownloadSize = cursor.getInt(6);
                @SuppressWarnings("unused")
                String sd_path = cursor.getString(7);
                String download_time = cursor.getString(8);
                int isbuild = cursor.getInt(9);
                int fileVersion = cursor.getInt(10);
                String fileName = cursor.getString(11);
                int downloadPriority = cursor.getInt(12);
                String packageName = cursor.getString(13);
                String downloadPathTwo = cursor.getString(14);
                long cateCode = cursor.getLong(15);
                String iconPicPath = cursor.getString(16);
                String suffixName = cursor.getString(17);
                int downloadSource = cursor.getInt(18);
                if (downloadSource == 0) {
                    downloadSource = DownloadInfo.DOWNLOAD_SOURCE_MAIN;
                }
                switch (type) {
                    case AbsDownloadInfo.APK_TYPE:
                        DownloadInfo myDownloadInfo = new DownloadInfo(downloadSource, cateCode, packageName,
                                fileVersion, download_path, downloadPriority);
                        myDownloadInfo.setState(state);
                        myDownloadInfo.setFileSize(fileSize);
                        myDownloadInfo.setThreadNum(threadNum);
                        myDownloadInfo.setAlreadyDownloadSize(alreadyDownloadSize);
                        myDownloadInfo.setRequestStartTime(Long.parseLong(download_time));
                        myDownloadInfo.setIsbuild(isbuild);
                        myDownloadInfo.setFileName(fileName);
                        myDownloadInfo.setDownloadPathTwo(downloadPathTwo);
                        myDownloadInfo.setIconPicPath(iconPicPath);
                        int percentage = (int) (myDownloadInfo.getFileSize() == 0 ? 0 : (myDownloadInfo
                                .getAlreadyDownloadSize() * 100) / myDownloadInfo.getFileSize());
                        myDownloadInfo.setDownloadPercentage(percentage);

                        // 如果存在文件显示。不存在不显示
                        if (alreadyDownloadSize == 0
                                || (alreadyDownloadSize > 0 && DownloadFilePathUtils.isHasSDFile(myDownloadInfo
                                        .getDownloadFilePath()))) {
                            canterMap.put(key, myDownloadInfo);
                        }
                        break;
                    case AbsDownloadInfo.OTHER_TYPE:
                        DownloadGeneral downloadGeneral = new DownloadGeneral(downloadSource, download_path, suffixName);
                        downloadGeneral.setState(state);
                        downloadGeneral.setFileSize(fileSize);
                        downloadGeneral.setThreadNum(threadNum);
                        downloadGeneral.setAlreadyDownloadSize(alreadyDownloadSize);
                        downloadGeneral.setRequestStartTime(Long.parseLong(download_time));
                        downloadGeneral.setIsbuild(isbuild);
                        downloadGeneral.setFileName(fileName);
                        downloadGeneral.setSuffixName(suffixName);
                        downloadGeneral.setDownloadPathTwo(downloadPathTwo);
                        int percentageOther = (int) (downloadGeneral.getFileSize() == 0 ? 0 : (downloadGeneral
                                .getAlreadyDownloadSize() * 100) / downloadGeneral.getFileSize());
                        downloadGeneral.setDownloadPercentage(percentageOther);

                        // 如果存在文件显示。不存在不显示
                        if (alreadyDownloadSize == 0
                                || (alreadyDownloadSize > 0 && DownloadFilePathUtils.isHasSDFile(downloadGeneral
                                        .getDownloadFilePath()))) {
                            canterMap.put(key, downloadGeneral);
                        }
                        break;
                }

            }
        } catch (Exception e) {
            DownloadLog.error(e);
        } finally {
            try {
                if (cursor != null) {
                    cursor.close();
                }
            } catch (Exception e) {
                DownloadLog.error(e);
                cursor = null;
            }
        }
    }

    private static int updateFileDetailed(String key, ContentValues valuse) {
        StringBuffer where = new StringBuffer();
        where.append(DownloadDetailesTables.KEY).append(" = '").append(key).append("'");
        SQLiteDatabase database = DownloadSQLiteOpenHelper.getIntance().getWritableDatabase();
        return database.update(DownloadDetailesTables.DOWNLOAD_DB_FILE_DETAILE, valuse, where.toString(), null);
    }

    private static long insertFileDetailed(ContentValues valuse) {
        SQLiteDatabase database = DownloadSQLiteOpenHelper.getIntance().getWritableDatabase();
        return database.insert(DownloadDetailesTables.DOWNLOAD_DB_FILE_DETAILE, null, valuse);
    }

    private static int deleteFileDetailed(String key) {
        SQLiteDatabase database = DownloadSQLiteOpenHelper.getIntance().getWritableDatabase();
        String whereClause = DownloadDetailesTables.KEY + " = '" + key + "'";
        int deleteNum = database.delete(DownloadDetailesTables.DOWNLOAD_DB_FILE_DETAILE, whereClause, null);
        return deleteNum;
    }

    @SuppressWarnings("unused")
    private static int updateThreadDetailed(String allKey, int threadId, ContentValues valuse) {
        StringBuffer where = new StringBuffer();
        where.append(DownloadDetailesTables.KEY).append(" = '").append(allKey).append("'");
        SQLiteDatabase database = DownloadSQLiteOpenHelper.getIntance().getWritableDatabase();
        return database.update(DownloadDetailesTables.DOWNLOAD_DB_THREAD_DETAILE, valuse, where.toString(), null);
    }

    @SuppressWarnings("unused")
    private static long insertThreadDetailed(ContentValues valuse) {
        SQLiteDatabase database = DownloadSQLiteOpenHelper.getIntance().getWritableDatabase();
        return database.insert(DownloadDetailesTables.DOWNLOAD_DB_THREAD_DETAILE, null, valuse);
    }

    @SuppressWarnings("unused")
    private static int deleteThreadDetailed(String key) {
        SQLiteDatabase database = DownloadSQLiteOpenHelper.getIntance().getWritableDatabase();
        String whereClause = DownloadDetailesTables.KEY + " = " + key;
        int deleteNum = database.delete(DownloadDetailesTables.DOWNLOAD_DB_THREAD_DETAILE, whereClause, null);
        return deleteNum;
    }

    /**
     * 封装参数为ContentValues
     * @param request
     * @return
     */
    private static ContentValues requestToValues(DownloadInfo downloadInfo) {
        ContentValues values = new ContentValues();
        values.put(DownloadDetailesTables.KEY, downloadInfo.getKey());
        values.put(DownloadDetailesTables.TYPE, downloadInfo.getType());
        values.put(DownloadDetailesTables.STATE, downloadInfo.getState());
        values.put(DownloadDetailesTables.DOWNLOAD_PATH, downloadInfo.getDownloadPath());
        if (downloadInfo.getFileSize() != 0) {
            values.put(DownloadDetailesTables.FILESIZE, downloadInfo.getFileSize());
        }
        if (downloadInfo.getThreadNum() != 0) {
            values.put(DownloadDetailesTables.THREAD_NUM, downloadInfo.getThreadNum());
        }
        if (downloadInfo.getDownloadFilePath() != null
                && !TextUtils.isEmpty(downloadInfo.getDownloadFilePath().toString())) {
            values.put(DownloadDetailesTables.SD_PATH, downloadInfo.getDownloadFilePath().toString());
        }
        if (downloadInfo.getRequestStartTime() != 0) {
            values.put(DownloadDetailesTables.DOWNLOAD_TIME, downloadInfo.getRequestStartTime());
        }
        if (downloadInfo.getDownloadSource() != 0) {
            values.put(DownloadDetailesTables.DOWNLOAD_SOURCE, downloadInfo.getDownloadSource());
        }
        values.put(DownloadDetailesTables.ISBUILD, downloadInfo.getIsbuild());
        values.put(DownloadDetailesTables.VERSION_CODE, downloadInfo.getVersionCode());
        if (!TextUtils.isEmpty(downloadInfo.getSuffixName())) {
            values.put(DownloadDetailesTables.SUFFIX_NAME, downloadInfo.getSuffixName());
        }
        if (!TextUtils.isEmpty(downloadInfo.getFileName())) {
            values.put(DownloadDetailesTables.FILE_NAME, downloadInfo.getFileName());
        }
        if (downloadInfo.getDownloadPriority() != 0) {
            values.put(DownloadDetailesTables.DOWNLOAD_PRIORITY, downloadInfo.getDownloadPriority());
        }

        if (!TextUtils.isEmpty(downloadInfo.getDownloadPathTwo())) {
            values.put(DownloadDetailesTables.DOWNLOAD_PATH_TWO, downloadInfo.getDownloadPathTwo());
        }
        values.put(DownloadDetailesTables.CATE_CODE, downloadInfo.getCateCode());
        values.put(DownloadDetailesTables.PACKAGE_NAME, downloadInfo.getPackageName());
        if (!TextUtils.isEmpty(downloadInfo.getIconPicPath())) {
            values.put(DownloadDetailesTables.ICON_PATH, downloadInfo.getIconPicPath());
        }
        values.put(DownloadDetailesTables.ALREADY_SIZE, downloadInfo.getAlreadyDownloadSize());
        return values;
    }

}
